/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package traffic;

import com.google.code.eventsonfire.EventHandler;
import com.google.code.eventsonfire.Events;
import entities.FireComplete;
import entities.FireDrawGraphics;
import entities.FireStopExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import resultado.ResultadoHolder;

/**
 *
 * @author Leonardo Lino
 */
public class GestorThreads implements Runnable {
    
    private int pedidos;
    private int segundos;
    private int numThreads;
    private ExecutorService executor;
    
    public static boolean metodo_list = false;
    public static boolean metodo_select = false;
    
    
    public GestorThreads(int pedidos, int segundos, 
            int numThreads, boolean metodo_list, boolean metodo_select){
      this.pedidos = pedidos;
      this.segundos = segundos;
      this.numThreads = numThreads;
      this.metodo_list = metodo_list;
      this.metodo_select=metodo_select;
      Events.bind(GeradorPanel.class, this);
    }

    @Override
    public void run() {
        ResultadoHolder.getInstance().clear();
        ResultadoHolder.getInstance().setSegundos(segundos);
        launchThreads();
    }
    
    private void launchThreads(){
        
        executor = Executors.newFixedThreadPool(numThreads);
        
        for (int i=0; i< numThreads; i++){
            TrafegoRunnable tr = new TrafegoRunnable(pedidos/numThreads, segundos);
            executor.execute(tr);
        }
        executor.shutdown();
       
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            System.err.println(e.toString());
        }
        
        ResultadoHolder holder = ResultadoHolder.getInstance();
        System.out.println("fail: " + holder.getFailSegundo(2));
        System.out.println("ok: " + holder.getOKsegundo(2));
        Events.fire(this, new FireDrawGraphics());
        Events.fire(this, new FireComplete());
        
    }
    
    @EventHandler
    public void handleEvent2(FireStopExecutor fire) {
       executor.shutdownNow();
    }
 

    
}
